﻿using RabbitMQ_Common;
using System;
using System.Collections.Generic;
using System.Text;

namespace RabbitMQ_Producer.Direct
{
    public class DirectProducer
    {
        public static void SendMessage(string message)
        {
            try
            {
                var connection = RabbitMQHelper.GetConnection();
                var channel = connection.CreateModel();

                //开启发布确认
                channel.ConfirmSelect();
                //声明交换机，direct(路由)模式
                channel.ExchangeDeclare("direct_exchange", "direct", true, false, null);

                //声明队列
                channel.QueueDeclare("direct_queue1", true, false, false, null);
                channel.QueueDeclare("direct_queue2", true, false, false, null);
                channel.QueueDeclare("direct_queue3", true, false, false, null);

                //队列绑定交换机
                channel.QueueBind("direct_queue1", "direct_exchange", "info", null);
                channel.QueueBind("direct_queue2", "direct_exchange", "warn", null);
                channel.QueueBind("direct_queue3", "direct_exchange", "error", null);

                //消息设置
                var properties = channel.CreateBasicProperties();
                //持久化
                properties.Persistent = true;

                //发布消息
                var body = Encoding.UTF8.GetBytes(message);
                channel.BasicPublish("direct_exchange", "info", false, properties, body);

                //等待消息确认
                if (channel.WaitForConfirms(new TimeSpan(0,0,10)))
                {
                    Console.WriteLine($"DirectProducer SendMessage Success:{message}");
                }
                else
                {
                    Console.WriteLine($"DirectProducer SendMessage WaitForConfirms Failed:{message}");
                }
                channel.Close();
                channel.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine($"DirectProducer SendMessage Failed:{e.Message}");
            }           
        }
    }
}
